package com.hckjsec.common.image;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

//生成签字图片
public class CenerateSignImage {
    public static BufferedImage drawTranslucentStringPic(int width, int height, Integer fontHeight, String drawStr)
    {
        try
        {
            BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D gd = buffImg.createGraphics();
            //设置透明  start
            buffImg = gd.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
            gd=buffImg.createGraphics();
            //设置透明  end
            gd.setFont(new Font("华文行楷", Font.BOLD, fontHeight)); //设置字体
            gd.setColor(Color.BLUE); //设置颜色
            gd.drawRect(0, 0, width - 1, height - 1); //画边框
            gd.drawString(drawStr, width/2-fontHeight*drawStr.length()/2,fontHeight); //输出文字（中文横向居中）
            return buffImg;
        } catch (Exception e) {
            return null;
        }
    }

    public static boolean getVenerateSign(String name,String path){
        BufferedImage imgMap = drawTranslucentStringPic(165, 70, 56,name);
        File imgFile=new File(path);
        boolean flag=true;
        try
        {
            ImageIO.write(imgMap, "PNG", imgFile);
        } catch (IOException e)
        {
            flag=false;
            e.printStackTrace();
        }
        return flag;
    }

    public static void ByteToFile(byte[] bytes,String path){
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        BufferedImage bi1 = null;
        try {
            bi1 = ImageIO.read(bais);
            File w2 = new File(path);//可以是jpg,png,gif格式
            ImageIO.write(bi1, "png", w2);//不管输出什么格式图片，此处不需改动
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                bais.close();
            } catch (IOException e) {

            }
        }
    }
}
